<template>
  <div class="main">
    <table>
      <tbody>
        <tr>
          <td>用户名</td>
          <td><input type="text" disabled v-model="username"></td>
        </tr>
        <tr>
          <td>旧密码</td>
          <td><input type="password" name="" id="" v-model="params.oldPassword">
          </td>
        </tr>
        <tr>
          <td>新密码</td>
          <td><input type="password" v-model="params.newPassword"></td>
        </tr>
        <tr>
          <td>确认密码</td>
          <td><input type="password" v-model="confirm"></td>
        </tr>
      </tbody>
    </table>
    <div class="btn" @click="modifyAccount">保存</div>
    <ModelDialog v-show="confirmModel">
      <template #body>
        <div class="modelMain">新密码和确认密码不同!</div>
      </template>
      <template #footer>
        <button class="button" @click="confirmModel = false">确认</button>
      </template>
    </ModelDialog>
    <ModelDialog v-show="wrong">
      <template #body>
        <div class="modelMain">密码错误!</div>
      </template>
      <template #footer>
        <button class="button" @click="wrong = false">确认</button>
      </template>
    </ModelDialog>
  </div>
</template>

<script setup>
import { reqGetUserInfo, reqModifyPswd } from '@/apis/user';
import ModelDialog from '@/components/ModelDialog.vue';
import userStore from '@/stores/modules/user';
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router';
let confirmModel = ref(false)
let wrong = ref(false)
let username = ref()
const $router = useRouter();
const params = reactive({
  id: userStore().userId,
  oldPassword: '',
  newPassword: ''
})
let confirm = ref()
onMounted(() => {
  getInfo()
})
const modifyAccount = async () => {
  if (params.newPassword !== confirm.value) {
    confirmModel.value = true
    return
  }
  let res = await reqModifyPswd(params)
  if (res.code == 201) {
    wrong.value = true
  } else {
    alert('修改成功')
    userStore().userLogout()
    //跳转到登录页面
    $router.push({ path: '/login' });
  }
}
const getInfo = async () => {
  const res = await reqGetUserInfo(userStore().userId)
  if (res.code === 200) {
    username.value = res.data.nickname
  }
}
</script>

<style lang="scss" scoped>
.main {
  margin: .3333rem;
  width: 100%;

  display: flex;
  flex-direction: column;
  justify-content: center;

  td {
    font-size: .3333rem;
    padding: .1667rem;
  }


  .btn {
    height: .6667rem;
    font-size: .4rem;
    color: #fff;
    background-color: #ff404e;
    margin: .1667rem auto;
    padding: 0 .15rem;
    text-align: center;
    line-height: .6667rem;
    border-radius: 10%;
    cursor: pointer;
  }

  input {
    border: .0167rem solid #aaa;
  }

  input[disabled] {
    border: .0167rem solid #ddd;
    cursor: not-allowed;
  }

}

.modelMain {
  margin: .1667rem;
}

.button {
  background-color: #bfb830;
  margin-left: .3333rem;
  border: none;
  border-radius: 20%;
  padding: .0833rem;
  color: #fff;
  cursor: pointer;
}
</style>